
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
#include <mysql/mysql.h>
#include <mysql/errmsg.h>

#include "receive_frame.h"
#include "print_data.h"
#include "frame_sql.h"
#include "unix_socket.h"

#define BAUDRATE        B115200
#define MODEDEVICE     "/dev/ttyS0"
#define _POSIX_SOURCE   1
#define DATA_LEN        30
#define HEAD_DATA				0xAAAA

MYSQL mysql;
struct termios oldtio, newtio;
int fd;
unsigned char* data;
unsigned char* get_frame;


unsigned short swap(unsigned char numh, unsigned char numl)
{
  unsigned short temp = 0;
  temp |= numh;
  temp <<= 8;
  temp |= numl;
  return temp;
}


int send_frame(unsigned char *, unsigned char);

void sighandler(int signo)
{
	if (signo == SIGINT)
	{
		printf("start to close program..");
		unix_socket_close(sockfd);
		close(fd);
		fclose(fdlog);
		tcsetattr(fd, TCSANOW, &oldtio);

		free(data);
		free(log_str);
		free(get_frame);
	}
	exit(0);
}

int main()
{
  int c = 0, res = 0;
  unsigned char buf[255];

	signal(SIGINT, sighandler);

	//Open log.txt
	fdlog = fopen("log.txt", "a+");
	if (NULL == fdlog)
	{
		perror("Open log file failed");
		exit(-1);
	}
	log_str = (char *)malloc(1024);


	//Initiaization mysql
	framedata_mysql_init(&mysql);
	//Initiaization unix_socket
	sockfd = unix_socket_init();


  //Open device
  printf("Open device...\n");
  //fd = open(MODEDEVICE, O_RDWR | O_NOCTTY | O_NDELAY);
  fd = open(MODEDEVICE, O_RDWR);
  if (-1 == fd) 
	{
		log_time = time(&log_time);
		memset(log_str, 0, 1024);
    sprintf(log_str, "%s  %-8s | line %-3d | %s : %s.\n", ctime(&log_time), __FILE__, __LINE__ - 4, "open device", strerror(errno));
		printf("%s", log_str);
		if (-1 == fwrite(log_str, 1, strlen(log_str), fdlog))
		{
			perror("Log write error:");
		}
		fflush(fdlog);
    exit(-1);
  }
	printf("Open device success.\n");
	sleep(1);

  printf("Open serial...\n");

  //Save serial configuration
  tcgetattr(fd, &oldtio);

  //Setup serial
  bzero(&newtio, sizeof(newtio));

  newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
  newtio.c_iflag = IGNPAR;
  newtio.c_oflag = 0;
  //newtio.c_lflag = ICANON;
  newtio.c_lflag = ~(ICANON | ECHO | ECHOE | ISIG);

  tcflush(fd, TCIFLUSH);
  if (-1 == tcsetattr(fd, TCSANOW, &newtio))
	{
		log_time = time(&log_time);
		memset(log_str, 0, 1024);
    sprintf(log_str, "%s  %-8s | line %-3d | %s : %s.\n", ctime(&log_time), __FILE__, __LINE__ - 4, "tcsetattr", strerror(errno));
		printf("%s\n", log_str);
		if (-1 == fwrite(log_str, 1, strlen(log_str), fdlog))
		{
			perror("Log write error:");
		}
		fflush(fdlog);
		exit(-1);
	}
  printf("Setup serial success.\n");

  int loop, data_num;
  int init_flag = 0;
  data = (unsigned char*)malloc(DATA_LEN);

	while (1) 
  {
    bzero(buf, 255);
    res = read(fd, buf, 255);
    if (res == 0 || res == -1)
    {
      continue;
    }
//    printf("res = %d\n", res);

		int i;
		for (i = 0; i < res; i++)
		{
			printf("%02X ", buf[i]);
		}
		printf("\n");

    loop = 0;
    if (init_flag == 0)
    {
      for (; loop < res; loop++) 
      {
				if (buf[loop] == ((HEAD_DATA >> 8) & 0xFF) && buf[loop + 1] == (HEAD_DATA & 0xFF))
        {
          init_flag = 1;
          data_num = 0;
          break;
        }
      }
    }


    if (init_flag != 0)
    {
      for (; loop < res; loop++, data_num++)
      {
        data[data_num] = buf[loop];
				if (data_num > 2 && (data[0] != 0xAA || data[1] != 0x1E))
				{
					init_flag = 0;
					break;
				}
        if (data_num > 8 && data_num == data[6] + 8)
        {
          get_frame = (unsigned char*)malloc(data_num + 1);
          memcpy(get_frame, data, data_num + 1);

          send_frame(get_frame,data_num + 1);

          bzero(data, DATA_LEN);
          data_num = 0;
          break;
        }
      }  
    }
    usleep(100000);
  }


  return 0;
}

//Send frame_data to server
int send_frame(unsigned char* data, unsigned char data_len)
{
/*
	if (framedata_mysql_compare(&mysql, data, data_len)!=0)
		return 0;
	*/	
	int loop = 0;
	int id;
  printf("frame data:\n");
  for (loop = 0; loop < data_len; loop++)
  {
    printf("%02X ", data[loop]);
  }
  printf("\n");

	id = framedata_mysql_insert(&mysql,data, data_len);

  switch(data[5])
  {
    case 0x92:
      print_92(&mysql, id, data, data_len);
      break;
    default:
      break;
  }
	return 0;
}

